package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.SyDatasetInfo;
import com.ruoyi.system.domain.SyFileInfo;
import com.ruoyi.system.domain.SyStation;
import com.ruoyi.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 站点信息表Controller
 * 
 * @author SYGIS
 * @date 2023-09-13
 */
@RestController
@RequestMapping("/system/station")
public class SyStationController extends BaseController {

    @Autowired
    private ISyStationService syStationService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISyFileInfoService fileInfoService;

    @Autowired
    private ISyDatasetInfoService datasetInfoService;

    /**
     * 查询站点信息表列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SyStation syStation) {
        startPage();
        List<SyStation> list = syStationService.selectSyStationList(syStation);
        if(list.size()>0){
            for(SyStation station:list){
                if(station.getChargerId()!=null){
                    SysUser user = userService.selectUserById(station.getChargerId());
                    if(user!=null){
                        station.setChargerName(user.getNickName());
                    }
                }

                if(station.getDeptId()!=null){
                    SysDept dept = deptService.selectDeptById(station.getDeptId());
                    if(dept!=null){
                        station.setDeptName(dept.getDeptName());
                    }
                }
            }
        }
        return getDataTable(list);
    }

    @PostMapping("/editStation")
    public AjaxResult editStation(@RequestBody SyStation syStation) {
        if(syStation.getUuid()==null){ //新增
            syStation.setUuid(UUID.randomUUID().toString().replaceAll("-", ""));
            syStation.setCreateBy(SecurityUtils.getLoginUser().getUserId().toString());
            syStation.setCreateTime(new Date());
            syStation.setStatus(0);
            syStationService.insertSyStation(syStation);
        }else{ //修改
            syStation.setUpdateBy(SecurityUtils.getLoginUser().getUserId().toString());
            syStation.setUpdateTime(new Date());
            syStationService.updateSyStation(syStation);
        }
        return AjaxResult.success();
    }

    /**
     * 导出站点信息表列表
     */
    @Log(title = "站点信息表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SyStation syStation) {
        List<SyStation> list = syStationService.selectSyStationList(syStation);
        ExcelUtil<SyStation> util = new ExcelUtil<SyStation>(SyStation.class);
        util.exportExcel(response, list, "站点信息表数据");
    }

    /**
     * 获取站点信息表详细信息
     */
    @GetMapping(value = "/{uuid}")
    public AjaxResult getInfo(@PathVariable("uuid") String uuid) {
        SyStation station = syStationService.selectSyStationByUuid(uuid);
        if(station!=null){
            if(station.getFileAttach()!=null){
                List<SyFileInfo> attachList = getAttachList(station.getFileAttach());
                station.setAttachList(attachList);
            }
            if(station.getChargerId()!=null){
                SysUser user = userService.selectUserById(station.getChargerId());
                if(user!=null){
                    station.setChargerName(user.getNickName());
                }
            }
            if(station.getDeptId()!=null){
                SysDept dept = deptService.selectDeptById(station.getDeptId());
                if(dept!=null){
                    station.setDeptName(dept.getDeptName());
                }
            }
            if(station.getCreateBy()!=null){
                SysUser user = userService.selectUserById(Long.parseLong(station.getCreateBy()));
                if(user!=null){
                    station.setCreator(user.getNickName());
                }
            }
        }
        return success(station);
    }

    public List<SyFileInfo> getAttachList(String attachUrl){
        String[] attachArray = null;
        if(attachUrl!=null){
            String url = attachUrl.replaceAll(" ","");
            if(url.length()>0){
                attachArray = attachUrl.split(",");
            }
        }
        List<SyFileInfo> list = new ArrayList<>();
        if(attachArray!=null){
            if(attachArray.length>0){
                for(String url:attachArray){
                    SyFileInfo fileInfo = new SyFileInfo();
                    fileInfo.setUrl(url);
                    List<SyFileInfo> files = fileInfoService.selectSyFileInfoList(fileInfo);
                    SyFileInfo file = files.get(0);
                    if(file!=null){
                        file.setName(file.getOriginName());
                    }
                    list.add(file);
                }
            }
        }
        return list;
    }

    /**
     * 新增站点信息表
     */
    @Log(title = "站点信息表", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SyStation syStation) {
        return toAjax(syStationService.insertSyStation(syStation));
    }

    /**
     * 修改站点信息表
     */
    @Log(title = "站点信息表", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SyStation syStation) {
        return toAjax(syStationService.updateSyStation(syStation));
    }

    /**
     * 删除站点信息表
     */
    @Log(title = "站点信息表", businessType = BusinessType.DELETE)
	@DeleteMapping("/{uuids}")
    public AjaxResult remove(@PathVariable String[] uuids) {
        return toAjax(syStationService.deleteSyStationByUuids(uuids));
    }

    @PostMapping("/processStartStation")
    public AjaxResult processStartStation(@RequestBody SyStation syStation) {
        SyStation station = syStationService.selectSyStationByUuid(syStation.getUuid());
        if(station!=null){
            station.setStatus(1);
            syStationService.updateSyStation(station);
            return AjaxResult.success();
        }else{
            return AjaxResult.error("没有找到对应的站点信息");
        }
    }

    @PostMapping("/processDeleteStation")
    public AjaxResult processDeleteStation(@RequestBody SyStation syStation) {
        SyStation station = syStationService.selectSyStationByUuid(syStation.getUuid());
        if(station!=null){
            syStationService.deleteSyStationByUuid(syStation.getUuid());
            return AjaxResult.success();
        }else{
            return AjaxResult.error("没有找到对应的站点信息");
        }
    }

    @PostMapping("/processRestartStation")
    public AjaxResult processRestartStation(@RequestBody SyStation syStation) {
        SyStation station = syStationService.selectSyStationByUuid(syStation.getUuid());
        if(station!=null){
            station.setStatus(1);
            syStationService.updateSyStation(station);
            return AjaxResult.success();
        }else{
            return AjaxResult.error("没有找到对应的站点信息");
        }
    }

    @PostMapping("/processFinishStation")
    public AjaxResult processFinishStation(@RequestBody SyStation syStation) {
        SyStation station = syStationService.selectSyStationByUuid(syStation.getUuid());
        if(station!=null){
            station.setStatus(2);
            syStationService.updateSyStation(station);
            return AjaxResult.success();
        }else{
            return AjaxResult.error("没有找到对应的站点信息");
        }
    }

    @PostMapping("/processNullifyStation")
    public AjaxResult processNullifyStation(@RequestBody SyStation syStation) {
        SyStation station = syStationService.selectSyStationByUuid(syStation.getUuid());
        if(station!=null){
            station.setStatus(3);
            syStationService.updateSyStation(station);
            return AjaxResult.success();
        }else{
            return AjaxResult.error("没有找到对应的站点信息");
        }
    }

    @GetMapping("/getRoleStationList")
    public AjaxResult getRoleStationList(SyStation param) {
        List<SyStation> list = new ArrayList<>();
        List<SyStation> unbindRoleList = syStationService.selectUnbindRoleList(param.getRoleIds());
        List<SyStation> bindRoleList = syStationService.selectBindRoleList(param.getRoleIds());
        if(unbindRoleList.size()>0){
            for (SyStation res:unbindRoleList){
                res.setHasRole(0);
                list.add(res);
            }
        }
        if(bindRoleList.size()>0){
            for (SyStation res:bindRoleList){
                res.setHasRole(1);
                list.add(res);
            }
        }
        return AjaxResult.success(list);
    }

    @PostMapping("/saveRoleStation")
    public AjaxResult saveRoleStation(@RequestBody SyStation param){
        String[] ids = param.getIds().split(",");
        if(ids.length>0) {
            for (String id : ids) {
                SyStation station = syStationService.selectSyStationByUuid(id);
                if(station!=null){
                    if(station.getRoleIds()!=null){
                        if(station.getRoleIds().indexOf(param.getRoleIds())<0){
                            station.setRoleIds(station.getRoleIds()+","+param.getRoleIds());
                        }
                    }else{
                        station.setRoleIds(param.getRoleIds());
                    }
                    syStationService.updateSyStation(station);
                }
            }
        }
        return AjaxResult.success();
    }

    @PostMapping("/unhookRoleStation")
    public AjaxResult unhookRoleStation(@RequestBody SyStation param) {
        SyStation station = syStationService.selectSyStationByUuid(param.getUuid());
        if(station!=null){
            if(station.getRoleIds()!=null){
                String roleIds = station.getRoleIds().replaceAll(","+param.getRoleIds(),"").replaceAll(param.getRoleIds(),"");
                station.setRoleIds(roleIds);
                syStationService.updateSyStation(station);
            }
        }
        return AjaxResult.success();
    }

    @GetMapping("/getBindRoleStationList")
    public AjaxResult getBindRoleStationList(SyStation param) {
        List<SyStation> list = new ArrayList<>();
        List<SyStation> bindRoleList = syStationService.selectBindRoleList(param.getRoleIds());
        if(bindRoleList.size()>0){
            for (SyStation res:bindRoleList){
                res.setHasRole(1);
                list.add(res);
            }
        }
        return AjaxResult.success(list);
    }

    @GetMapping("/getDatasetStationList")
    public AjaxResult getDatasetStationList(SyStation param) {
        List<SyStation> list = syStationService.selectDatasetStationList();
        if(list.size()>0){
            for(SyStation station:list){
                List<SyDatasetInfo> datasets = datasetInfoService.selectDatasetByUuidAndStationId(param.getUuid(),station.getUuid());
                if(datasets.size()>0){
                    station.setHasRole(1);
                }else{
                    station.setHasRole(0);
                }
            }
        }
        return AjaxResult.success(list);
    }

    @PostMapping("/saveDatasetStation")
    public AjaxResult saveDatasetStation(@RequestBody SyStation param){
        SyDatasetInfo dataset = datasetInfoService.selectSyDatasetInfoByUuid(param.getUuid());
        if(dataset!=null){
            if(dataset.getStationIds()!=null){
                String[] ids = param.getIds().split(",");
                if(ids.length>0) {
                    for (String id : ids) {
                        if(dataset.getStationIds().indexOf(id)<0){
                            dataset.setStationIds(dataset.getStationIds()+","+id);
                        }
                    }
                }
            }else{
                dataset.setStationIds(param.getIds());
            }
        }
        datasetInfoService.updateSyDatasetInfo(dataset);
        return AjaxResult.success();
    }

    @PostMapping("/unhookDatasetStation")
    public AjaxResult unhookDatasetStation(@RequestBody SyStation param){
        SyDatasetInfo dataset = datasetInfoService.selectSyDatasetInfoByUuid(param.getUuid());
        if(dataset!=null){
            String stationIds = dataset.getStationIds().replaceAll(","+param.getIds(),"").replaceAll(param.getIds(),"");
            dataset.setStationIds(stationIds);
            datasetInfoService.updateSyDatasetInfo(dataset);
        }
        return AjaxResult.success();
    }

    @GetMapping("/getBindDatasetStationList")
    public AjaxResult getBindDatasetStationList(SyStation param) {
        SyDatasetInfo dataset = datasetInfoService.selectSyDatasetInfoByUuid(param.getUuid());
        List<SyStation> list = new ArrayList<>();
        if(dataset!=null){
            if(dataset.getStationIds()!=null){
                if(dataset.getStationIds().length()>0){
                    String[] ids = dataset.getStationIds().split(",");
                    if(ids.length>0) {
                        for (String id : ids) {
                            if(id.replaceAll(" ","").length()>0){
                                SyStation station = syStationService.selectSyStationByUuid(id);
                                if(station!=null){
                                    station.setHasRole(1);
                                    list.add(station);
                                }
                            }
                        }
                    }
                }
            }
        }
        return AjaxResult.success(list);
    }
}
